/**
 * 
 * 2021/10/19 10:42:00
 * 
*/
// 内置库
import fs = require('fs');
import path = require('path');
import express = require('express');
import axios = require('axios');
// 核心
import { Core } from './Core';
import { Config } from './Config';

// 启动
const start = () => {
	let config = JSON.parse(fs.readFileSync(
		path.join(__dirname,'/../config.json')
	).toString());
	log(`\x1B[36m ----- 正在启动 端口:::${config.port} ----- \x1B[0m`);
	log('LMApi 服务开始运行 开始检测授权状态');
	fs.stat(path.join(__dirname,'/../authorization.log'), function (err, stats) {
		if(err) {
    		console.error(err);
    		log('authorizationa.log文件不存在！请自行创建！')
    		return false;
    	}
    	if(stats.isFile()) {
    		log('授权文件存在 开始验证授权状态');
    	}
	});
	return config;
}

let webConfig = start();

const http = new Core(webConfig,axios);

const app: express.Application = express();

/* Web 路由区*/ 
app.use(express.static(path.join(__dirname, '/../docs')));

app.get('/', (req , res) => {
	res.send('这是首页!');
});

// 下载数据
app.get('/data/download', (req , res) => {
	if(req.query['dict'] == undefined) {
		res.json(json(false,'请求参数不存在'));
		return;
	}
	if(Config[ req.query['dict'] ] == undefined) {
		res.json(json(false,'字典参数不正确'));
		return;
	}
	let download = http.download(req.query['dict']);
	download.then(r => {
		if(undefined == r.data.success) {
			console.log(r.data);
			log(Config[req.query['dict']] + ' 获取失败');
			res.json(json(false,'获取失败'));
			return;
		}
		if(r.data.success == true) {
			res.json(json(true,'获取成功',r.data.rows));
			return;
		}
	}).catch(error => {
    	let msg = error.response.data.msg
    	log(msg)
    	if (msg.search('请重新登录') > 0) {
    		log('刷新token');
    		http.token();
    	}
    	// 重定向再次请求
    	download.then(r => {
			if(undefined == r.data.success) {
				console.log(r.data);
				log(Config[req.query['dict']] + ' 获取失败');
				res.json(json(false,'获取失败'));
				return;
			}
			if(r.data.success == true) {
				res.json(json(true,'获取成功',r.data.rows));
				return;
			}
		})
    });
});

app.listen(webConfig.port, () => {
	log(`LMApi 服务运行成功！ http://localhost:${webConfig.port}`)
});

/* 工具区 */

// 控制台日志
function log(t) {
	let date = new Date();
	let d = date.getFullYear() + '年' + (date.getMonth()+1) +'月' + date.getDate() + '日 ' 
	+ date.getHours()+':' + date.getMinutes() +':' + date.getSeconds();
	console.log(`[\x1B[90m${d}]\x1B[39m ${t}`);
}
// json响应
function json(success,msg,data=false) {
	return {
		success,msg,data
	}
}